const app = getApp();
import util from '../../utils/util'
import {
  EventShow,
  GetIsseuChuLi,
  CheckIsseuGrder,
  GetMenu,
  GetGriderRrole,
  GetVollegeInfo,
  GetGriderList,
  GetGrid,
  GetGridNum,
  GetFocalList,
  GetImportManNum,
  GetGriderHome,

  GetShiveList,
  GetGrider,
  GetGriderZhang,
  FeedbackNum,
  UpEvent
} from '../../config/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    defaultOption: {},
    identity: 18,
    rolesArr: [],
    adminInfo: '',
    ishaveSub: 0, // 默认0 无
    daily_menu: [], //日常菜单
    person_infos: '', // 人口户籍信息
    manage_menu: [], // 管理菜单
    vollege_info: '',
    // master_grider: '', // 网格员列表
    grid_info: '', //网格信息
    grid_nums: '', // 数据数量

    grider_master_info: '', // 网格长信息
    feedback_num: '',
    villagerEvent: [], // 村民事件
    flag: false, //是否弹出网格长详情，默认不显示
    ucid: '',
    Isshow: false, //是否展示网格员弹窗，默认不显示

    grider_info: {}, // 测试网格员信息
    member: '',
    grider_storge: {},
    grid_manage: '',
    grid_important_num: 0,
    roles: '', // 角色名称
    rolesObj: '', // 职责对象
    rolesConArr: [], // 职责数组
    griderInfoItem: '', // 网格员信息项
    showGriderPopup: false, // 是否显示网格员信息
    chageGrid: false,
    grider_arr: [],
    xiaji_data: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    if (!wx.getStorageSync('adminInfo') && !wx.getStorageSync('member') && !wx.getStorageSync("userArr") && wx.getStorageSync("userArr").length == 0) {
      wx.redirectTo({
        url: '/pages/register/register',
      })
    }

    this.getVollegeInfo(); // 获取村信息

    let adminInfo = wx.getStorageSync('adminInfo');
    if (adminInfo) {
      this.setData({
        adminInfo,
        'grider_storge.id': 0
      })
      this.getDailyMenu(); // 获取我的工作台菜单
      this.getNewestEvent(); // 事件展示
      return;
    }

    that.setData({
      member: wx.getStorageSync('member')
    })

    let userArr = wx.getStorageSync("userArr")
    if (userArr.length == 1 && userArr[0].authorize == 18) {
      that.setData({
        identity: 18
      })
    } else {
      let rolesArr = [];
      userArr.forEach(function(item, index) {
        if (item.authorize != 18) {
          rolesArr.push(item)
        }
      })
      console.log('rolesArr:', rolesArr)
      that.setData({
        rolesArr
      })

      //默认显示最高角色
      if (rolesArr.length == 1) {
        that.setData({
          identity: rolesArr[0].authorize,
          grider_storge: rolesArr[0]
        })
        wx.setStorageSync('grider', rolesArr[0])
      } else {
        let min = rolesArr[0].authorize;
        let top_role = {};
        rolesArr.forEach(function(item, index) {
          if (item.authorize <= min) {
            top_role = item;
            that.setData({
              identity: item.authorize,
              defaultOption: {
                id: item.authorize,
                name: item.roles
              }
            })
          }
        })
        that.setData({
          grider_storge: top_role
        })
        wx.setStorageSync('grider', top_role)
        console.log('最高角色值：', top_role)
      }
    }

    let grider_storge = wx.getStorageSync("grider")
    if (adminInfo || this.data.member || grider_storge) {} else {
      wx.redirectTo({
        url: '/pages/register/register',
      })
      return;
    }

    if (!grider_storge) { // 正式开启，测试注释
      console.log('村民页面')
      this.getGrider();
      this.getShiveList()
      // this.getFeedbackNum()
      return;
    }

    if (this.data.identity != 18) {
      if (this.data.identity == 12) {
        console.log('网格长角色')
        this.setData({
          grider_master_info: grider_storge
        })
        this.getGrid();
      } else {
        console.log('网格其他角色')
        console.log("grider_storge:", grider_storge)
        this.setData({ // 网格员测试注释，正式开启
          grider_info: grider_storge
        })
        this.getGridMaster(); // 获取网格长、网格员、网格
        this.getGriderHome(); // 获取网格员数据数量
      }
      this.GetIsseuChuLi(); // 下级动态数
      this.checkIsseuGrder();
      this.getGridNum();
      this.getDailyMenu(); // 获取日常菜单
      this.getManageMenu() // 管理菜单
      this.getNewestEvent(); // 事件展示
    }
  },

  changeRole(value) {
    let that = this;
    console.log("切换：", value)
    let rolesArr = this.data.rolesArr;
    for (let i = 0; i < rolesArr.length; i++) {
      if (value.detail.id == rolesArr[i].authorize) {
        that.setData({
          grider_storge: rolesArr[i]
        })
        wx.setStorageSync("grider", rolesArr[i])
      }
    }
    this.setData({
      identity: value.detail.id,
    })
    if (this.data.identity == 12) {
      console.log('网格长角色')
      this.setData({
        grider_master_info: this.data.grider_storge
      })
      this.getGrid();
    } else {
      console.log('网格其他角色')
      console.log("grider_storge:", this.data.grider_storge)
      this.setData({ // 网格员测试注释，正式开启
        grider_info: this.data.grider_storge
      })
      this.getGridMaster(); // 获取网格长、网格员、网格
      this.getGriderHome(); // 获取网格员数据数量
    }
    this.GetIsseuChuLi(); // 下级动态数
    this.checkIsseuGrder();
    this.getGridNum();
    this.getDailyMenu(); // 获取日常菜单
    this.getManageMenu() // 管理菜单
    this.getNewestEvent(); // 事件展示
  },

  checkIsseuGrder() {
    let that = this;
    let params = {
      vollege_id: app.globalData.vollege_id,
      id: that.data.grider_storge.id
    }
    util.apiRequest(CheckIsseuGrder, params, null).then(r => {
      console.log('是否有下级：', r)
      that.setData({
        ishaveSub: r.data.data
      })
    })
  },

  //网格切换事件
  bindChageGrid(e) {
    let id = e.currentTarget.dataset.id
    let grider_arr = wx.getStorageSync('grider_arr');
    for (var i = 0; i < grider_arr.length; i++) {
      if (id == grider_arr[i].id) {
        wx.setStorageSync('grider', grider_arr[i])
        this.onLoad();
      }
    }
  },
  getVollegeInfo() { // 获取村信息
    util.apiRequest(GetVollegeInfo, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('村信息：', r)
      this.setData({
        vollege_info: r.data.data.reverse()
      })
    })
  },

  getGriderRrole() { // 获取职责
    let that = this;
    console.log('roles', this.data.roles)
    let params = {
      roles: this.data.roles,
      vollege_id: app.globalData.vollege_id
    }
    util.apiRequest(GetGriderRrole, params, null).then(r => {
      console.log('职责r：', r)
      if (r.data.data.length != 0) {
        let rolesConStr = r.data.data[0].content.replace(/\n/g, "|-&");
        let rolesConArr = rolesConStr.split("|-&");
        that.setData({
          rolesConArr,
          rolesObj: r.data.data[0]
        })
      }
    })
  },

  getDailyMenu() { // 网格日常菜单
    let that = this;
    let params = {
      belongs: "daily_manage",
      vollege_id: app.globalData.vollege_id,
      id: that.data.grider_storge.id
    }
    util.apiRequest(GetMenu, params, null).then(r => {
      console.log('日常菜单：', r)
      that.setData({
        daily_menu: r.data.data,
        person_infos: r.data.topinfo
      })
    })
  },

  getManageMenu() { // 网格日常菜单
    let that = this;
    let params = {
      belongs: 4,
      vollege_id: app.globalData.vollege_id,
      id: that.data.grider_storge.id
    }
    util.apiRequest(GetMenu, params, null).then(r => {
      console.log('管理菜单：', r)
      that.setData({
        manage_menu: r.data.data
      })
    })
  },

  // AAAA网格长
  // 获取网格长下的网格员信息
  // getGriderList() {
  //   let that = this;
  //   util.apiRequest(GetGriderList, {
  //     id: that.data.grider_master_info.id
  //   }, null).then(r => {
  //     console.log('网格长下网格员：', r)
  //     that.setData({
  //       master_grider: r.data.data.data
  //     })
  //   })
  // },

  // 获取网格信息
  getGrid() {
    let that = this;
    util.apiRequest(GetGrid, {
      id: that.data.grider_master_info.id
    }, null).then(r => {
      console.log('网格信息：', r)
      that.setData({
        grid_info: r.data.data
      })
    })
  },

  // 网格长下数据个数
  getGridNum() {
    let that = this;
    util.apiRequest(GetGridNum, {
      id: that.data.grider_master_info.id
    }, null).then(r => {
      console.log('数据数量', r)
      that.setData({
        grid_nums: r.data.data
      })
    })
  },

  // AAAAAAAAA网格员AAAAAAAAAAAAAAAAA
  // 获取网格长信息
  getGridMaster() {
    let that = this;
    let pid = this.data.grider_info.pid;
    util.apiRequest(GetGriderZhang, {
      id: pid
    }, null).then(r => {
      console.log('2网格长信息:', r)
      that.setData({
        grider_master_info: r.data.data
      })
      // that.getGriderList() // 获取网格员
      that.getGrid() // 获取所属网格
    })
  },

  getGriderHome() { // 获取网格员数据数量
    let that = this;
    util.apiRequest(GetGriderHome, {
      id: that.data.grider_info.id
    }, null).then(r => {
      console.log('2网格员数量：', r)
      that.setData({
        grid_nums: r.data.data
      })
    })
  },

  // toEventList(e) { // 网格长/网格员跳转事件列表
  //   let cat_id = e.currentTarget.dataset.cat_id;
  //   wx.navigateTo({
  //     url: '/pages/grid/griderEventList/griderEventList?cat_id=' + cat_id,
  //   })
  // },

  // onIssues() { // 事件发布
  //   wx.navigateTo({
  //     url: '/pages/grid/submit_problem/submit_problem',
  //   })
  // },

  toImportantList(e) {
    let that = this;
    var vollege_id = that.data.grider_storge.vollege_id
    wx.navigateTo({
      url: '/pages/grid/key_groups/key_groups?vollege_id=' + vollege_id,
    })
  },

  //获取重点人群数
  // getImportManNum() {
  //   let that = this;
  //   var vollege_id = that.data.grider_storge.vollege_id
  //   util.apiRequest(GetImportManNum, {
  //     vollege_id: vollege_id
  //   }, null).then(r => {
  //     console.log('重点人群数：', r)
  //     that.setData({
  //       grid_important_num: r.data.data.total
  //     })
  //   })
  // },

  // AAAAAAAAAA村民
  // 获取网格员信息
  getGrider() {
    let that = this;
    util.apiRequest(GetGrider, {
      id: this.data.member.grider_id
    }, null).then(r => {
      console.log('0获取上级信息', r)
      that.setData({
        grider_info: r.data.data
      })

      wx.setStorageSync('grider_info', r.data.data) // 存储网格员信息

      that.getGriderMonitor()
    })
  },

  // 获取网格长信息
  getGriderMonitor() {
    let that = this;
    let pid = this.data.grider_info.pid;
    console.log('pid', pid)
    util.apiRequest(GetGriderZhang, {
      id: pid
    }, null).then(r => {
      console.log('网格长信息:', r)
      that.setData({
        grider_master_info: r.data.data
      })
      this.getGrid() // 获取网格信息
    })
  },

  // 获取上级反馈数量
  getFeedbackNum() {
    let that = this;
    util.apiRequest(FeedbackNum, {
      id: this.data.member.id
    }, null).then(r => {
      console.log('未读：', r)
      that.setData({
        feedback_num: r.data.data
      })
    })
  },

  //村民事件
  getShiveList() {
    let that = this;
    util.apiRequest(GetShiveList, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('村民事件', r)
      that.setData({
        villagerEvent: r.data.data
      })
    })
  },

  //村民——跳转到提交页面
  toVillagerForm(e) {
    // let ucid = e.currentTarget.dataset.ucid;
    // let town_id = e.currentTarget.dataset.town_id;
    wx.navigateTo({
      url: '/pages/grid/villager_form/villager_form'
    })
  },

  /**
   * 关闭弹窗
   */
  CloseDialog: function() {
    this.setData({
      Isshow: false
    });
  },

  /**
   * 拨打电话
   */
  Dial: function() {
    console.log('您点击了拨打电话！');
    wx.makePhoneCall({
      phoneNumber: this.data.grider_info.mobile //
    });

    let params = {
      nick_name: this.data.member.nick_name,
      town_id: this.data.member.town_id,
      vollege_id: this.data.member.vollege_id,
      cat_id: 3,
      helper: this.data.member.grider_id,
      puid: this.data.member.id,
      ucid: 4,
      addr: this.data.member.committees + this.data.member.address,
      u_name: this.data.member.name,
      p_name: this.data.member.name,
      h_name: this.data.grider_info.name,
      uid: this.data.member.id
    }
    util.apiRequest(UpEvent, params).then(r => {
      console.log('拨打电话', r)
    })
  },

  /**
   * 点击查看网格长
   */
  CheckGridOrder: function(e) {
    let roles = e.currentTarget.dataset.roles;
    console.log('roles:', roles)

    console.log('点击查看网格长/员');
    let that = this;
    that.setData({
      roles,
      flag: true
    });

    this.getGriderRrole();
  },

  checkGriderInfo(e) { // 查看网格员信息
    let item = e.currentTarget.dataset.item;
    console.log('网格员信息1111:', item)

    this.setData({
      roles: item.roles,
      griderInfoItem: item,
      showGriderPopup: true
    });

    this.getGriderRrole();
  },

  /**
   * 电话诉求弹窗
   */
  telephonePopup: function(e) {
    console.log('村民查看网格员！');
    let roles = e.currentTarget.dataset.roles;
    let ucid = e.currentTarget.dataset.ucid;
    this.setData({
      roles,
      ucid: ucid,
      Isshow: true
    });
    this.getGriderRrole();
  },

  /**
   * 关闭详情
   */
  Close: function() {
    console.log('您点击了关闭按钮！');
    let that = this;
    that.setData({
      flag: false,
      showGriderPopup: false
    });
  },

  /**
   * 查看网格员
   */
  CheckMore: function() {
    console.log('您点击了查看更多网格员！');
    wx.navigateTo({
      url: '/pages/grid/grid_detail/grid_detail'
    });
  },

  toVillagerForm() { // 村民发布问题
    wx.navigateTo({
      url: '/pages/grid/villager_form/villager_form',
    })
  },

  // 我的下级动态
  toEventList(e) { // 事件处理

    let type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/grid/griderIsseuEventList/griderIsseuEventList?type=' + type,
    })
  },

  toEventList1(e) { // 电话诉求跳转

    let type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/grid/getPhoneAppealList/getPhoneAppealList?type=' + type,
    })
  },

  toEventList2(e) { // 

    let type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/grid/getIsseuSjrwList/getIsseuSjrwList?type=' + type,
    })
  },

  GetIsseuChuLi() {
    let that = this;
    let id = this.data.grider_storge.id;
    util.apiRequest(GetIsseuChuLi, {
      vollege_id: app.globalData.vollege_id,
      id: id
    }, null).then(r => {
      console.log('下级处理首页', r)
      if (r.data.code == 0) {
        // wx.showToast({
        //   title: r.data.info,
        //   icon: 'none',
        //   duration: 2000
        // })
      }
      that.setData({
        xiaji_data: r.data.data
      })
    })
  },

  // 事件展示区域
  getNewestEvent() {
    let that = this;
    util.apiRequest(EventShow, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log("事件展示：", r)
      that.setData({
        newest_event: r.data.data
      })
    })
  },

  checkDetail(e) {
    let id = e.currentTarget.dataset.id;
    let cat_id = e.currentTarget.dataset.cat_id;
    let status = e.currentTarget.dataset.status;
    let show = e.currentTarget.dataset.show;

    if (cat_id == 1) {
      wx.navigateTo({
        url: '/pages/grid/grider_feedback_detail/grider_feedback_detail?id=' + id + '&status=' + status + '&show=' + show,
      })
    } else {
      wx.navigateTo({
        url: '/pages/grid/unresolvedDetail/unresolvedDetail?id=' + id + '&status=' + status + '&show=' + show
      })
    }
  },
  // END 事件展示区域

})